package com.zjzywl.smoke.repository;

import java.util.Date;
import java.util.List;
import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.zjzywl.smoke.entity.Device;


/**
 * 设备装置
 * @author s
 *
 */
@Repository
public interface DeviceRepository extends JpaRepository<Device,Integer>,DeviceCustomRepository {
	//根据设备编码获取设备
	@Query("select u from Device u where devCode=:devCode")
	Device findByDeviceCode(@Param("devCode") String devCode);

	//统计设备数量
	@Query("select count(u) from Device u where u.usestatus=1")
	Integer countDevice();
	@Query("select count(u) from Device u where u.usestatus=1 and u.deviceType.deviceTypeId=:deviceTypeId")
	Integer countDeviceByDeviceType(@Param("deviceTypeId") String deviceTypeId);
	
	//获取有效的设备
	@Query("select u from Device u where u.usestatus=1 and u.Remove=null")
	List<Device> validDevice();
	@Query("select u from Device u where u.usestatus=1 and u.deviceType.deviceTypeId=:deviceTypeId")
	List<Device> validDeviceByDeviceType(@Param("deviceTypeId") String deviceTypeId);
	
	//根据安装日期获取设备
	@Query("select u from Device u where u.installationDate <=:installationDate")
	List<Device> findByInstallationDateBefore(@Param("installationDate") Date installationDate);
	@Query("select u from Device u where u.installationDate <=:installationDate and u.deviceType.deviceTypeId=:deviceTypeId")
	List<Device> findByInstallationDateBeforeAndDeviceType(@Param("installationDate") Date installationDate,@Param("deviceTypeId") String deviceTypeId);
	
	//按照地址模糊查询
	List<Device> findByAddressLike(String address);
	
	@Query("select u from Device u where u.deviceType.deviceTypeId=:deviceTypeId and u.address like :address")
	List<Device> findByDeviceTypeAndAddressLike(@Param("address") String address,@Param("deviceTypeId") String deviceTypeId);
	

	@Query("select u from Device u where locate(:address,address)>0")
	List<Device> findDeviceByaddressLoc(@Param("address") String address);

	//按设备类型查询设备
	@Query("select u from Device u where u.deviceType.deviceTypeId=:deviceTypeId")
	List<Device> findByDeviceType(@Param("deviceTypeId") String deviceTypeId);
	@Transactional
	@Modifying
	@Query("update Device u set u.fireCount=:fireCount where  devCode=:devCode")
	void updateFirCount(@Param("devCode")String devCode, @Param("fireCount")int fireCount);
	@Transactional
	@Modifying
	@Query(value = "update  Device u set  Remove='删除' where id=:id ") 
	void deleteDevice(@Param("id")Integer id);
	@Query("select u from Device u where u.Remove=null")
	List<Device> findAllDevices();


}
